package com.yzq.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzq.annotation.AuthCheck;
import com.yzq.common.Result;
import com.yzq.constant.UserConstant;
import com.yzq.enums.ErrorCode;
import com.yzq.enums.SpaceLevelEnum;
import com.yzq.exception.BusinessException;
import com.yzq.manager.auth.SpaceUserAuthManager;
import com.yzq.model.dto.space.SpaceAddRequest;
import com.yzq.model.dto.space.SpaceLevel;
import com.yzq.model.dto.space.SpaceQueryRequest;
import com.yzq.model.dto.space.SpaceUpdateRequest;
import com.yzq.model.entity.Space;
import com.yzq.model.vo.SpaceVO;
import com.yzq.model.vo.UserVO;
import com.yzq.service.SpaceService;
import com.yzq.service.UserService;
import com.yzq.utils.ThrowUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "空间管理")
@RestController
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    @ApiOperation("添加空间")
    @PostMapping("/add")
    public Result<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.BAD_REQUEST);
        long newId = spaceService.addSpace(spaceAddRequest, request);
        return Result.success(newId);
    }

    @ApiOperation("删除空间")
    @DeleteMapping("/delete")
    public Result<Boolean> deleteSpace( @RequestParam Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null, ErrorCode.BAD_REQUEST);
        UserVO loginUser = userService.getCurrentUser(request);
        // 判断是否存在
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND);
        // 仅本人或者管理员可删除
        spaceService.checkSpaceAuth(oldSpace,request);
        // 操作数据库
        boolean result = spaceService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }


    @ApiOperation("更新空间")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.BAD_REQUEST);
        }
        // 将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        // 数据校验
        spaceService.validSpace(space, false);
        // 判断是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取空间
     */
    @ApiOperation("获取空间信息")
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public Result<SpaceVO> getSpaceById(@RequestParam Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null, ErrorCode.BAD_REQUEST);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND);
        UserVO currentUser = userService.getCurrentUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, currentUser);
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        spaceVO.setPermissionList(permissionList);
        // 获取封装类
        return Result.success(spaceVO);
    }

    /**
     * 根据 用户id 获取空间列表
     */
    @ApiOperation("根据用户id获取空间列表")
    @GetMapping("/list/byUserId")
    public Result<List<Space>> listSpaceByUserId(HttpServletRequest request) {
        UserVO loginUser = userService.getCurrentUser(request);
        return Result.success(spaceService.listSpaceByUserId(loginUser.getId()));
    }

    /**
     * 分页获取空间列表（仅管理员可用）
     */
    @ApiOperation("分页获取空间列表")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Result<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getPageNum();
        long size = spaceQueryRequest.getPageSize();
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return Result.success(spacePage);
    }

    /**
     * 分页获取空间列表（封装类）
     */
    @ApiOperation("分页获取空间列表（封装类）")
    @PostMapping("/list/page/vo")
    public Result<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                         HttpServletRequest request) {
        long current = spaceQueryRequest.getPageNum();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.BAD_REQUEST);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 获取封装类
        return Result.success(spaceService.getSpaceVOPage(spacePage, request));
    }




    @ApiOperation("获取空间等级列表")
    @GetMapping("/list/level")
    public Result<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return Result.success(spaceLevelList);
    }


}
